import path from "path";
import { ROOT_DIR } from "../util/path_util";
import { existsSync, readFileSync } from "fs";

export type McpServer = {
    name?: string;
    description?: string;
    command: string;
    args?: string[];
    env?: any;
    inputSchema?: {
        type: "object";
        properties: { [key: string]: any };
        required: string[];
    };
};

export type FunctionCallTool = {
    type: "function";
    function: {
        name: string;
        description: string;
        parameters: {
            type: "object";
            properties: { [key: string]: any };
            required: string[];
        };
    };
};

export type McpConfig = {
    mcpServers?: { [key: string]: McpServer };
};

export function convertMCPToolsToOpenAIFormat(mcpServers: McpServer[]): any[] {
    return mcpServers.map((serverConfig) => {
        const converted: FunctionCallTool = {
            type: "function",
            function: {
                name: serverConfig.name || "",
                description:
                    serverConfig.description ||
                    `Use the ${serverConfig.name} tool`,
                parameters: {
                    type: "object",
                    properties: serverConfig.inputSchema?.properties || {},
                    required: serverConfig.inputSchema?.required || [],
                },
            },
        };
        return converted;
    });
}

export function readMcpConfig(): McpConfig {
    const configPath = path.join(ROOT_DIR, "mcp.config.json");
    if (!existsSync(configPath)) {
        return {};
    }
    let config = readFileSync(configPath, "utf-8");
    if (!config) {
        return {};
    }
    const mcpConfig: McpConfig = JSON.parse(config);
    return mcpConfig;
}
